import { defineStore } from 'pinia'
import { ref } from 'vue'

import {
  ascending,
  type cacheType,
  constantMenus,
  debounce,
  filterNoPermissionTree,
  filterTree,
  formatFlatteningRoutes,
  getKeyList,
} from '../utils'
import { useMultiTagsStore } from './multiTags'

export const usePermissionStore = defineStore('pure-permission', () => {
  // state
  const wholeMenus = ref<any[]>([])
  const flatteningRoutes = ref<any[]>([])
  const cachePageList = ref<any[]>([])

  /**
   * 组装整体路由生成的菜单
   *
   * @param routes
   */
  function handleWholeMenus(routes: any[]) {
    const data = filterTree(ascending(constantMenus.concat(routes)))
    wholeMenus.value = filterNoPermissionTree(data)
    flatteningRoutes.value = formatFlatteningRoutes(constantMenus.concat(routes) as any)
  }

  function cacheOperate({ mode, name }: cacheType) {
    const delIndex = cachePageList.value.indexOf(name)
    switch (mode) {
      case 'refresh':
        cachePageList.value = cachePageList.value.filter(v => v !== name)
        break
      case 'add':
        cachePageList.value.push(name)
        break
      case 'delete':
        delIndex !== -1 && cachePageList.value.splice(delIndex, 1)
        break
    }
    /** 监听缓存页面是否存在于标签页，不存在则删除 */
    debounce(() => {
      let cacheLength = cachePageList.value.length
      const nameList = getKeyList(useMultiTagsStore().multiTags, 'name')
      while (cacheLength > 0) {
        !nameList.includes(cachePageList.value[cacheLength - 1]) &&
          cachePageList.value.splice(
            cachePageList.value.indexOf(cachePageList.value[cacheLength - 1]),
            1,
          )
        cacheLength--
      }
    })()
  }

  /** 清空缓存页面 */
  function clearAllCachePage() {
    wholeMenus.value = []
    cachePageList.value = []
  }

  return {
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus,
    // 整体路由（一维数组格式）
    flatteningRoutes,
    // 缓存页面keepAlive
    cachePageList,
    // 方法
    handleWholeMenus,
    cacheOperate,
    clearAllCachePage,
  }
})
